package com.bawei.module_mine.adapter

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.bawei.lib_storage.database.entity.HistoryVideoEntity
import com.bawei.module_mine.databinding.ItemHistoryVideoBinding
import com.bumptech.glide.Glide
import java.text.SimpleDateFormat
import java.util.*

class HistoryAdapter(
    private val onItemClick: (HistoryVideoEntity) -> Unit,
    private val onDeleteClick: (HistoryVideoEntity) -> Unit
) : ListAdapter<HistoryVideoEntity, HistoryAdapter.HistoryViewHolder>(HistoryDiffCallback()) {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): HistoryViewHolder {
        val binding = ItemHistoryVideoBinding.inflate(
            LayoutInflater.from(parent.context),
            parent,
            false
        )
        return HistoryViewHolder(binding)
    }

    override fun onBindViewHolder(holder: HistoryViewHolder, position: Int) {
        holder.bind(getItem(position))
    }

    inner class HistoryViewHolder(
        private val binding: ItemHistoryVideoBinding
    ) : RecyclerView.ViewHolder(binding.root) {

        private val dateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault())

        fun bind(historyItem: HistoryVideoEntity) {
            binding.apply {
                tvCollectHistoryTitle.text = historyItem.title
                tvCollectHistoryDescription.text = historyItem.description
                tvCollectHistoryTime.text = dateFormat.format(Date(historyItem.watchTime))
                
                // 格式化观看时长
                val durationText = formatDuration(historyItem.watchDuration)

                // 设置点击事件
                root.setOnClickListener {
                    onItemClick(historyItem)
                }
                // 这里可以加载视频封面图片
                // 使用Glide或其他图片加载库
                 Glide.with(ivCollectHistoryCover).load(historyItem.coverUrl).into(ivCollectHistoryCover)
            }
        }
        
        private fun formatDuration(durationMs: Long): String {
            if (durationMs <= 0) return "未知"
            
            val totalSeconds = durationMs / 1000
            val minutes = totalSeconds / 60
            val seconds = totalSeconds % 60
            
            return if (minutes > 0) {
                "${minutes}分${seconds}秒"
            } else {
                "${seconds}秒"
            }
        }
    }

    private class HistoryDiffCallback : DiffUtil.ItemCallback<HistoryVideoEntity>() {
        override fun areItemsTheSame(oldItem: HistoryVideoEntity, newItem: HistoryVideoEntity): Boolean {
            return oldItem.id == newItem.id
        }

        override fun areContentsTheSame(oldItem: HistoryVideoEntity, newItem: HistoryVideoEntity): Boolean {
            return oldItem == newItem
        }
    }
} 